<?php
namespace App\Api\Admin\Controllers;

use App\Enum\ActivityEnum;
use App\Exceptions\ApiException;
use App\Models\Admin\Log;
use App\Models\Admin\Activity;
use Faker\Test\Calculator\IbanTest;
use Illuminate\Http\Request;
use App\Services\ActivityService;
use App\Models\MediaLikeStatic;
use App\Models\LikeStaticSettlement;
use App\Enum\MediaLikeStaticEnum;
use Illuminate\Support\Facades\DB;
use App\Models\AdminUser;

class ActivityController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @desc 添加活动配置
     * @return array
     * @throws \Exception
     */
    public function AddActivity()
    {
        $params['start_time'] = IT('start_time', true, '请选择活动开始时间');
        $params['end_time'] = IT('end_time', true, '请选择活动结束时间');
        $params['content'] = IT('content', true, '活动内容不能为空');
        $params['activity_strategy'] = IT('activity_strategy', true, '请输入奖金设置');
        $params['settlement_type'] = IT('settlement_type', true, '请输入奖励结算周期');
        $params['status'] = IT('status', true, '请输入活动状态');
        $params['operator_id'] = $this->user['id'];

        $rs = ActivityService::add_activity($params);
        if($rs['code'] != 0) {
            return json_error($rs['msg']);
        }

        (new Log)->add($this->user, '增加活动配置成功-'.$rs['activity_id']);
        return json_success('ok');
    }

    /**
     * @desc 编辑活动配置
     * @return array
     * @throws \Exception
     */
    public function EditActivity()
    {
        $params['id'] = IT('id', true, '请选择需要修改的活动');
        $params['start_time'] = IT('start_time', true, '请选择活动开始时间');
        $params['end_time'] = IT('end_time', true, '请选择活动结束时间');
        $params['content'] = IT('content');
        $params['activity_strategy'] = IT('activity_strategy');
        $params['settlement_type'] = IT('settlement_type');
        $params['status'] = IT('status', true, '请输入活动状态');
        $params['activity_photos'] = IT('activity_photos');
        $params['last_show_time'] = IT('last_show_time');
        $params['operator_id'] = $this->user['id'];

        $rs = ActivityService::modify_activity($params);
        if($rs['code'] != 0) {
            return json_error($rs['msg']);
        }

        (new Log)->add($this->user, '修改活动配置成功-'.$params['id']);
        return json_success('ok');
    }

    /**
     * @desc 获取活动配置列表
     * @param Request $request
     * @return array
     */
    public function GetActivityList(Request $request)
    {
        $page = max(1, (int) $request->input('page'));
        $page_size = (int) $request->input('pagesize');
        $page_size = $page_size ?: 20;
        $offset = ($page - 1) * $page_size;
        $total = Activity::where([])->count();
        $fields = ['id', 'content', 'start_time', 'end_time', 'activity_type', 'status', 'created_at', 'updated_at', 'activity_photos', 'last_show_time'];
        $activity_list = Activity::where([])->skip($offset)->take($page_size)->orderBy('updated_at', 'desc')->get($fields);
        $total_page = ceil($total / $page_size);
        if($activity_list) {
            foreach($activity_list as &$activity) {
                $activity['type_name'] = ActivityEnum::$activity_type_conversion[$activity['activity_type']];
                $activity['start_time'] = time2date($activity['start_time']);
                $activity['end_time'] = time2date($activity['end_time']);
                $activity['activity_photos'] = $activity['activity_photos'] ? getSignUrl($activity['activity_photos']) : '';
                $activity['last_show_time'] = $activity['last_show_time'] ? time2date($activity['last_show_time']) : '';
            }
        }

        return json_success('ok', ['totalpage' => $total_page,'total'=>$total, 'list' => $activity_list]);
    }

    /**
     * @desc 获取活动配置详情
     * @return array
     */
    public function GetActivityDetails()
    {
        $id = IT('id', true, '请选择修改的活动配置');

        $fields = ['id', 'content', 'start_time', 'end_time', 'settlement_type', 'activity_strategy', 'status', 'created_at', 'updated_at', 'activity_photos', 'activity_type', 'last_show_time'];
        $activity_info = Activity::select($fields)->where(['id' => $id])->first();
        if(empty($activity_info)) {
            return json_error('活动配置数据异常');
        }

        $activity_info = $activity_info->toArray();
        $activity_info['start_time'] = time2date($activity_info['start_time']);
        $activity_info['end_time'] = time2date($activity_info['end_time']);
        $activity_info['activity_strategy'] = json_decode($activity_info['activity_strategy'], true);
        $activity_info['activity_photos'] = $activity_info['activity_photos'] ? getSignUrl($activity_info['activity_photos']) : '';
        $activity_info['last_show_time'] = $activity_info['last_show_time'] ? time2date($activity_info['last_show_time']) : '';
        return json_success('ok', $activity_info);
    }

    /**
     * @desc 处理活动图片
     * @return array
     */
    public function confirm_upload_activity(){
        $img_file = IT('activity_photos', true, '请上传活动图片');
        if (!strpos($img_file, 'oss-cn-shenzhen.aliyuncs.com')) {
            return json_error('参数有误');
        }
        $img_file = getSignUrl($img_file);
        $return = array(
            'img_url' => $img_file
        );
        return json_success('上传成功', $return);
    }

    /**
     * @desc 视频征集活动列表
     */
    public function like_static_list()
    {
        $request_time = IT('time', date('Y-m-d H:i:s'));
        $like_static_type = IT('like_static_type', MediaLikeStaticEnum::MEDIA_LIKE_STATIC_TYPE_WEEK);
        $page = IT('page', 1);
        $page_size = IT('pagesize', 15);
        $mobile = IT('mobile');
        $uid = IT('uid');

        if($like_static_type == MediaLikeStaticEnum::MEDIA_LIKE_STATIC_TYPE_WEEK) {
            $show_settlement = ((int)date('W', strtotime($request_time)) < ((int)date('W'))) ? true : false;
            $date_format = $request_time ?date('W',strtotime($request_time)) : date('W');
        } else {
            $show_settlement = ((int)date('Ym', strtotime($request_time)) < ((int)date('Ym'))) ? true : false;
            $date_format = $request_time ? date('Ym', strtotime($request_time)) : date('Ym');
        }

        $mobile_where = [];
        if($mobile) {
            $mobile_where[] = ['mobile', 'like', '%'.$mobile.'%'];
        }

        $where_arr = [
            'type' => $like_static_type,
            'date_format' => $date_format
        ];

        $offset = ($page - 1) * $page_size;
        $fields = ['ivy_media_like_static.id as like_static_id', 'ivy_media_like_static.uid', 'users.mobile', 'users.name as user_name', 'users.avatar','users.name as user_name', 'ivy_media_like_static.like_num', 'ivy_media_like_static.update_time'];
        $like_static_list = DB::table('ivy_media_like_static')
            ->join('users', function($join) use($mobile_where) {
                $join->on('users.id', '=', 'ivy_media_like_static.uid')->where('users.status', 1);
                if($mobile_where) {
                    $join->where($mobile_where);
                }
            })
            ->where(function ($query) use($uid){ if($uid) {
                $query->where([['ivy_media_like_static.uid', 'like', '%'.$uid.'%']]);
            }})
            ->where($where_arr)
            ->skip($offset)
            ->take($page_size)
            ->orderBy('ivy_media_like_static.like_num', 'DESC')
            ->orderBy('ivy_media_like_static.update_time', 'ASC')
            ->orderBy('ivy_media_like_static.id', 'ASC')
            ->get($fields);
        $total = DB::table('ivy_media_like_static')
            ->join('users', function($join) use($mobile_where) {
                $join->on('users.id', '=', 'ivy_media_like_static.uid')->where('users.status', 1);
                if($mobile_where) {
                    $join->where($mobile_where);
                }
            })
            ->where(function ($query) use($uid){ if($uid) {
                $query->where([['ivy_media_like_static.uid', 'like', '%'.$uid.'%']]);
            }})
            ->where($where_arr)
            ->count();

        if($like_static_list) {
            foreach($like_static_list as &$like_static) {
                $sql = "SELECT * FROM (SELECT a.*, (@rowno:=@rowno+1) as rowno  FROM ivy_media_like_static a,(select (@rowno:=0)) b WHERE a.type={$like_static_type} and a.date_format={$date_format} ORDER BY a.like_num DESC,a.update_time ASC,a.id ASC) c WHERE c.uid={$like_static->uid}";
                $ranking_info = DB::select($sql);
                $like_static->ranking = $ranking_info[0]->rowno;
                $like_static->show_settlement = 0; // 不显示
                if($show_settlement  && $like_static->ranking <= 3) {
                    if(LikeStaticSettlement::where(['like_static_id' => $like_static->like_static_id])->first()) {
                        $like_static->show_settlement = 1; // 已结算
                    } else {
                        $like_static->show_settlement = 2; // 待结算
                    }
                }
                $like_static->avatar = $like_static->avatar ? getSignUrl($like_static->avatar) : '';
                $like_static->update_time = time2date($like_static->update_time);
            }
        }

        $total_page = (int)ceil($total/$page_size);

        return json_success('ok', ['total'=>$total,'totalPage' => $total_page, 'list' => $like_static_list]);
    }

    /**
     * @desc 视频征集活动详情
     */
    public function like_static_details() {
        //$uid = IT('uid', true, '请选择查看的用户');
        $like_static_id = IT('like_static_id', true, '请选择查看集赞的活动');
        $page = IT('page', 1);
        $page_size = IT('pagesize', 20);

        $like_static_info = MediaLikeStatic::where(['id' => $like_static_id])->first();
        if(empty($like_static_info)) {
            return json_error('数据异常');
        }


        // 处理指定周或月的时间范围
        if($like_static_info->type == MediaLikeStaticEnum::MEDIA_LIKE_STATIC_TYPE_WEEK) {
            $date_info = $this->get_week(date('Y', $like_static_info->create_time),$like_static_info->date_format);
        } else {
            $year = substr($like_static_info->date_format,0, 4);
            $month = substr($like_static_info->date_format,4, 2);
            $date_info = [
                'start' => date('Y-m-01 00:00:00', strtotime($year.'-'.$month)),
                'end' => date('Y-m-t 23:59:59', strtotime($year.'-'.$month))
            ];
        }

        $uid = $like_static_info->uid;
        $offset = ($page - 1) * $page_size;

        $fields = ['media_like.uid', 'media_like.media_id','users.name as user_name', 'users.avatar', 'users.mobile', 'users.created_at as reg_time', 'users.role', 'users.membership', 'media_like.created_at as like_time'];
        $like_static_list = DB::table('media_like')
            ->join('media', function($join) use ($uid) {
                $join->on('media.id', '=', 'media_like.media_id')->where('media.is_participate_activity', 1);
                if($uid) {
                    $join->where(['media.uid' => $uid]);
                }
            })
            ->join('users', function($join) {
                $join->on('users.id', '=', 'media_like.uid')->where('users.status', 1);
            })
            ->where(function($query) use($date_info) {
                $query->whereBetween('media_like.created_at',[$date_info['start'], $date_info['end']]);
            })
            ->skip($offset)
            ->take($page_size)
            ->orderBy('media_like.created_at', 'DESC')
            ->get($fields);
        $total = DB::table('media_like')
            ->join('media', function($join) use ($uid) {
                $join->on('media.id', '=', 'media_like.media_id')->where('media.is_participate_activity', 1);
                if($uid) {
                    $join->where(['media.uid' => $uid]);
                }
            })
            ->join('users', function($join) {
                $join->on('users.id', '=', 'media_like.uid')->where('users.status', 1);
            })
            ->where(function($query) use($date_info) {
                $query->whereBetween('media_like.created_at',[$date_info['start'], $date_info['end']]);
            })
            ->count();

        if($like_static_list) {
            foreach($like_static_list as &$like_static) {
                $like_static->avatar = $like_static->avatar ? getSignUrl($like_static->avatar) : '';
                if($like_static->role == 1) {
                    $like_static->identity_name = '股东用户';
                } elseif($like_static->membership == 1) {
                    $like_static->identity_name = '会员用户';
                } else {
                    $like_static->identity_name = '普通用户';
                }
            }
        }

        $total_page = (int)ceil($total/$page_size);

        return json_success('ok', ['total'=>$total,'totalPage' => $total_page, 'list' => $like_static_list]);
    }

    public static function get_week($year,$week)
    {
        $year_start = mktime(0,0,0,1,1,$year);
        $year_end = mktime(23,59,59,12,31,$year); // 判断第一天是否为第一周的开始
        if (intval(date('W',$year_start))===1){
            $start = $year_start;   // 把第一天做为第一周的开始
        }else{
            $week++;
            $start = strtotime('+1 monday',$year_start); // 把第一个周一作为开始
        }

        // 第几周的开始时间
        if ($week===1){
            $weekday['start'] = date('Y-m-d 00:00:00',$start);
        }else{
            $weekday['start'] = date('Y-m-d 00:00:00',strtotime('+'.($week-1).' monday',$start));
        }
        // 第几周的结束时间
        $weekday['end'] = date('Y-m-d 23:59:59',strtotime('+1 sunday',strtotime($weekday['start'])));
        if (date('Y',strtotime($weekday['end']))!=$year){
            $weekday['end'] = date('Y-m-d  23:59:59',$year_end);
        }return $weekday;
    }

    /**
     * @desc 视频征集活动奖励结算
     */
    public function like_static_settlement()
    {
        $like_static_id = IT('like_static_id', true, '请选择结算的用户');
        $reward_amount = IT('settlement_money', true, '请输入结算金额');
        $like_static_info = MediaLikeStatic::where(['id' => $like_static_id])->first();
        if(!$like_static_info) {
            return json_error('数据不存在');
        }
        if($like_static_info->type == MediaLikeStaticEnum::MEDIA_LIKE_STATIC_TYPE_WEEK) {
            if($like_static_info->date_format >= date('W')) {
                return json_error('本周的活动暂不能结算');
            }
        } else {
            if($like_static_info->date_format >= date('Ym')) {
                return json_error('本月的活动暂不能结算');
            }
        }

        $sql = "SELECT * FROM (SELECT a.*, (@rowno:=@rowno+1) as rowno  FROM ivy_media_like_static a,(select (@rowno:=0)) b WHERE a.type={$like_static_info->type} and a.date_format={$like_static_info->date_format} ORDER BY a.like_num DESC,a.update_time ASC,a.id ASC) c WHERE c.uid={$like_static_info->uid}";
        $ranking_info = DB::select($sql);
        if($ranking_info[0]->rowno > 3) {
            return json_error('排名前三名的才能结算');
        }

        $is_record = LikeStaticSettlement::where(['like_static_id' => $like_static_id])->first();
        if($is_record) {
            return json_error('已经结算');
        }

        $data = [
            'uid' => $like_static_info->uid,
            'like_static_id' => $like_static_id,
            'settlement_time' => time(),
            'reward_amount' => $reward_amount,
            'operator_id' => $this->user['id'],
            'ranking' => $ranking_info[0]->rowno
        ];

        $rs = LikeStaticSettlement::insert($data);
        if(!$rs) {
            return json_error('结算失败');
        }
        return json_success('ok', []);
    }

    /**
     * @return 视频征集榜单奖励结算日志
     */
    public function like_static_settlement_list() {
        $start_time = IT('start_time');
        $end_time = IT('end_time');
        $page = IT('page', 1);
        $page_size = IT('pagesize', 20);
        $mobile = IT('mobile');
        $uid = IT('uid');

        $mobile_where = [];
        if($mobile) {
            $mobile_where[] = ['mobile', 'like', '%'.$mobile.'%'];
        }

        $offset = ($page - 1) * $page_size;
        $fields = ['ivy_like_static_settlement.id', 'ivy_like_static_settlement.uid', 'ivy_like_static_settlement.settlement_time', 'ivy_like_static_settlement.reward_amount', 'ivy_like_static_settlement.ranking',
            'ivy_like_static_settlement.operator_id', 'users.mobile', 'users.name as user_name', 'users.avatar', 'ivy_media_like_static.type', 'ivy_media_like_static.date_format'];
        $like_settlement_list = DB::table('ivy_like_static_settlement')
            ->join('users', function($join) use($mobile_where) {
                $join->on('users.id', '=', 'ivy_like_static_settlement.uid')->where('users.status', 1);
                if($mobile_where) {
                    $join->where($mobile_where);
                }
            })
            ->join('ivy_media_like_static', function($join) {
                $join->on('ivy_media_like_static.id', '=', 'ivy_like_static_settlement.like_static_id');
            })
            ->where(function ($query) use($start_time,$end_time){ if(strtotime($start_time) && strtotime($end_time)) {
                $query->whereBetween('settlement_time',[strtotime($start_time), strtotime($end_time)]);
            }})
            ->where(function ($query) use($uid){ if($uid) {
                $query->where([['ivy_like_static_settlement.uid', 'like', '%'.$uid.'%']]);
            }})
            ->skip($offset)
            ->take($page_size)
            ->orderBy('ivy_like_static_settlement.id', 'DESC')
            ->get($fields);
        $total = DB::table('ivy_like_static_settlement')
            ->join('users', function($join) use($mobile_where) {
                $join->on('users.id', '=', 'ivy_like_static_settlement.uid')->where('users.status', 1);
                if($mobile_where) {
                    $join->where($mobile_where);
                }
            })
            ->join('ivy_media_like_static', function($join) {
                $join->on('ivy_media_like_static.id', '=', 'ivy_like_static_settlement.like_static_id');
            })
            ->where(function ($query) use($start_time,$end_time){ if(strtotime($start_time) && strtotime($end_time)) {
                $query->whereBetween('settlement_time',[strtotime($start_time), strtotime($end_time)]);
            }})
            ->where(function ($query) use($uid){ if($uid) {
                $query->where([['ivy_like_static_settlement.uid', 'like', '%'.$uid.'%']]);
            }})
            ->count();

        if($like_settlement_list) {
            foreach($like_settlement_list as &$like_settlement) {
                $like_settlement->settlement_time = time2date($like_settlement->settlement_time);
                $like_settlement->avatar = $like_settlement->avatar ? getSignUrl($like_settlement->avatar) : '';
                $like_settlement->operator_name = AdminUser::where(['id' => $like_settlement->operator_id])->value('name');
            }
        }

        $total_page = (int)ceil($total/$page_size);

        return json_success('ok', ['total'=>$total,'totalPage' => $total_page, 'list' => $like_settlement_list]);
    }
}